package cn.touna.jss.common.util;

import de.odysseus.staxon.json.JsonXMLConfig;
import de.odysseus.staxon.json.JsonXMLConfigBuilder;
import de.odysseus.staxon.json.JsonXMLInputFactory;
import de.odysseus.staxon.json.JsonXMLOutputFactory;
import de.odysseus.staxon.xml.util.PrettyXMLEventWriter;

import javax.xml.stream.*;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Staxon xml json 互转工具类
 * xml 转为 json 后 属性带有@符号,同理,json转xml xml标签属性也需要带有@符号 否则会转为子节点
 * 属性必须紧跟在所在节点后,不然会报错.所以在添加时,建议用LinkedHashMap转json 或者new JSONObject(true);
 */
public class StaxonUtil {
    /**
     * json string convert to xml string
     */
    public static String json2xml(String json) throws XMLStreamException, IOException {
        StringReader input = new StringReader(json);
        StringWriter output = new StringWriter();
        JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
        try {
            XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
            XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
            writer = new PrettyXMLEventWriter(writer);
            writer.add(reader);
            reader.close();
            writer.close();
        } finally {
            output.close();
            input.close();
        }
        /*if (output.toString().length() >= 38) {//remove <?xml version="1.0" encoding="UTF-8"?>
            return output.toString().substring(39);
        }*/
        return output.toString();
    }

    /**
     * xml string convert to json string
     */
    public static String xml2json(String xml) throws XMLStreamException, IOException {
        StringReader input = new StringReader(xml);
        StringWriter output = new StringWriter();
        JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(true).prettyPrint(true).build();
        try {
            XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
            XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
            writer.add(reader);
            reader.close();
            writer.close();
        } finally {
            output.close();
            input.close();
        }
        return output.toString();
    }
}
